package server;
import java.net.*;
import java.nio.charset.*;


import java.lang.*;
import server.User;
import java.io.*;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class myServer {
       public static void main(String[] args) throws IOException{
		ServerSocket ss=new ServerSocket(6666);
		System.out.println("server is running...");
		for (;;) {
            Socket sock = ss.accept();
            System.out.println("connected from " + sock.getRemoteSocketAddress());
            Thread t = new Handler(sock);
            t.start();
        }
	}
       
}

class Handler extends Thread{
	private Socket sock;
	private toDB mytoDB;
	
	public Handler(Socket s) throws IOException {
		this.sock=s;
		mytoDB=new toDB();
	}
	@Override
	public void run() {
	    try {
            InputStream input = this.sock.getInputStream();
            OutputStream output = this.sock.getOutputStream();
            handle(input,output);
        }catch (Exception e){
            try {
                this.sock.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            System.out.println("client disconnected.   ---Exception");
        }
        System.out.println("client disconnected.   ---Normal");
    }

    private void handle(InputStream input, OutputStream output) throws IOException, ClassNotFoundException, SQLException {
        ObjectOutputStream writer=new ObjectOutputStream(output);
        ObjectInputStream reader=new ObjectInputStream(input);
        //接收指令
        String cmd=(String)reader.readObject();

        String[] parameters=cmd.split("#");
        //判断指令类型,单指令or双指令
        if(!cmd.endsWith("#")){
            if(parameters[0].equals("UserRegister")){//注册
                User userm=mytoDB.query(parameters[0],parameters[1],parameters[2]);
                if(userm!=null)
                    writer.writeObject(userm.getName());
                else writer.writeObject("FALSE");
            }else if(parameters[0].equals("UserLogin")){//登录
                User userm=mytoDB.query(parameters[0],parameters[1],parameters[2]);
                System.out.println("at user login");
                System.out.println(userm.getSchedules());
                writer.writeObject(userm);
            }else if(parameters[0].equals("set_Plan")){//设置学习计划
            	System.out.println("at set plan");
                if(mytoDB.setPlan(parameters[1],parameters[2],Integer.parseInt(parameters[3])))
                    writer.writeObject("TRUE");
                else writer.writeObject("FALSE");
            }else if(parameters[0].equals("queryWords")){//请求单词，学习或复习
                System.out.println(cmd);
                LinkedHashMap<String,Word> words=
                        mytoDB.queryWords(parameters[1],parameters[2],parameters[3],Integer.parseInt(parameters[4]));
                System.out.println("queryWords");
                System.out.println(words);
                writer.writeObject(words);
            }else if(parameters[0].equals("updateUserMessage")){//管理用户信息
                if(mytoDB.updateUserMessage(parameters[1],parameters[2],parameters[3]))
                    writer.writeObject("TRUE");
                else writer.writeObject("FALSE");
            }else if(parameters[0].equals("queryWord")){//查单词
                Word word=mytoDB.queryWord(parameters[1]);
                if(word!=null)
                System.out.println(word.getWord()+" "+word.getPhone()+" "+word.getSynos());
                writer.writeObject(word);
            }else if(parameters[0].equals("queryDictionaryAll")){//查询词库信息 ALL
                writer.writeObject(mytoDB.queryDictionaryAll());
            }else if(parameters[0].equals("queryDictionary")){//查询词库信息  单个
                writer.writeObject(mytoDB.queryDictionary(parameters[1]));
            }else if(parameters[0].equals("updateUserSchedule")){
                if(mytoDB.updateUserSchedule(parameters[1],parameters[2],Integer.parseInt(parameters[3])))
                    writer.writeObject("TRUE");
                else writer.writeObject("FALSE");
            }else{//错误指令
                writer.writeObject("FALSE CMD");
            }
        }else{
            if(parameters[0].equals("updateDictionaryWords")){//更新词库--单词组
                LinkedHashMap<String,Word> words=(LinkedHashMap<String,Word>)reader.readObject();
                if(mytoDB.updateDictionaryWords(parameters[1],parameters[2],words))
                    writer.writeObject("TRUE");
                else writer.writeObject("FALSE");
            }else if(parameters[0].equals("updateDictionaryFiles")){//更新词库--文件
                File file=(File)reader.readObject();
                if(mytoDB.updateDictionaryFiles(file))
                    writer.writeObject("TRUE");
                else writer.writeObject("FALSE");
            }else{//错误指令
                writer.writeObject("FALSE CMD");
            }
        }

        //关闭流
        writer.close();
        reader.close();
    }
}

class toDB{
    private final String varStrW = "(word varchar(50),phone varchar(50),synos text)";
    private final String varStrP = "(name varchar(50),password varchar(50),plan varchar(50),speed varchar(50))";
    private UserDB userDB;
    private WordDB wordDB;
	public toDB() throws IOException {
        wordDB = new WordDB("worddb","cet4",varStrW);
        userDB = new UserDB("persondb","person",varStrP);
	}
    //用户注册or登录
	public User query(final String type,final String name,final String password) throws IOException {
        if(type.equals("UserRegister")){//注册
            if(userDB.register(name,password))//检测是否重名
                return userDB.getUserMessage(name);
            else return null;
        }else{//登录
            if(userDB.login(name,password))//验证账户密码
                return userDB.getUserMessage(name);
            else return null;
        }
	}
	//用户设置计划
	public boolean setPlan(final String username,final String dictionaryLevel,final int daily_plan){
	    return userDB.setUserPlan(username,dictionaryLevel,daily_plan);
	}
	//请求单词
	public LinkedHashMap<String,Word> queryWords(final String id,final String dictionaryname,final String type,final int amount){
		
		if(type.equals("Study")) {
			int from=userDB.getUserStudySpeed(id, dictionaryname);
			int to=from+amount;
			return wordDB.getStudyWords(dictionaryname, from, to);
		}
		else {
			int end=userDB.getUserStudySpeed(id, dictionaryname);
			int numb=amount;
			if(amount>end) numb=end;
			return wordDB.getReviewWords(dictionaryname, end, numb);
		}
	}
	//更新用户进度
    public boolean updateUserSchedule(final String dictionryname,final String username,final Integer amount){
        return userDB.addUserStudySpeed(username,dictionryname,amount);
    }
	//查询全部词库信息
	public Map<String,Integer> queryDictionaryAll() throws SQLException {
	    HashMap<String,Integer> result=new HashMap<String, Integer>();
        List<String> dicts=wordDB.queryTable();
        for(String i:dicts)
            result.put(i,wordDB.getCountOfDictionary(i));
        System.out.println("queryDictionaryall");
        return result;
    }
    public int queryDictionary(String dictionaryname){
	    return wordDB.getCountOfDictionary(dictionaryname);
    }
	//更新用户信息
	public boolean updateUserMessage(final String id,final String type,final String operate){
		return false;
	}
	//更新词库信息   --单词组
	public boolean updateDictionaryWords(final String dictionarylevel,final String operate,final LinkedHashMap<String,Word> words){
		return false;
	}
	//更新词库信息   --文件
	public boolean updateDictionaryFiles(File file){
		return false;
	}
	//单词查询
	public Word queryWord(final String spell){
		Word word=wordDB.findWord(spell);
		return word;
	}
}


